package com.nantong.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantong.admin.domain.SysPermission;
import com.nantong.admin.domain.SysRole;
import com.nantong.admin.domain.model.response.permission.SysPermissionVo;
import com.nantong.admin.mapper.SysPermissionMapper;
import com.nantong.admin.mapper.SysRoleMapper;
import com.nantong.admin.service.ISysPermissionService;
import com.nantong.admin.util.LoginHelper;
import com.nantong.common.core.enums.commonEnums.StatusEnum;
import com.nantong.common.core.utils.MapstructUtils;
import com.nantong.common.core.utils.TreeBuildUtils;
import com.nantong.common.mybatis.core.page.PageQuery;
import com.nantong.common.mybatis.core.page.TableDataInfo;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;

/**
 * 权限 业务层处理
 *
 * @author nantong
 */
@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

    private final SysPermissionMapper permissionMapper;
    private final SysRoleMapper roleMapper;

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public List<SysPermission> selectPermissionsByUserId(Long userId) {
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
            // 查询所有有效的权限
            LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysPermission::getStatus, StatusEnum.ENABLE.getCode());
            return baseMapper.selectList(wrapper);
        }
        // 普通用户按照角色查询权限
        return permissionMapper.selectPermissionsByUserId(userId);
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public List<SysPermission> selectPermissionsByRoleId(Long roleId) {

        return permissionMapper.selectPermissionsByRoleId(roleId);
    }

    /**
     * 根据用户ID查询权限标识
     *
     * @param userId 用户ID
     * @return 权限标识列表
     */
    @Override
    public Set<String> listPermissionKeysByUserId(Long userId) {

        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
            perms.add("*:*:*");
        } else {
            perms.addAll(permissionMapper.selectPermissionKeysByUserId(userId));
        }
        return perms;
    }

    /**
     * 校验权限名称是否唯一
     *
     * @param permission 权限信息
     * @return 结果
     */
    @Override
    public boolean checkPermissionNameUnique(SysPermission permission) {
        Long permissionId = permission.getPermissionId() == null ? -1L : permission.getPermissionId();
        LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermission::getPermissionName, permission.getPermissionName());
        SysPermission info = permissionMapper.selectOne(queryWrapper);
        return info == null || info.getPermissionId().equals(permissionId);
    }

    /**
     * 校验权限标识是否唯一
     *
     * @param permission 权限信息
     * @return 结果
     */
    @Override
    public boolean checkPermissionKeyUnique(SysPermission permission) {
        Long permissionId = permission.getPermissionId() == null ? -1L : permission.getPermissionId();
        LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPermission::getPermissionKey, permission.getPermissionKey());
        SysPermission info = permissionMapper.selectOne(queryWrapper);
        return info == null || info.getPermissionId().equals(permissionId);
    }


    /**
     * 查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysPermissionVo> listPermissions(Long userId) {

        List<SysPermissionVo> menuList;
        // 管理员显示所有菜单信息
        if (LoginHelper.isSuperAdmin(userId)) {
            LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysPermission::getStatus, StatusEnum.ENABLE.getCode());
            menuList = permissionMapper.selectVoList(wrapper);
        } else {
            List<SysPermission> list = permissionMapper.listPermissionByUserId(userId);
            menuList = MapstructUtils.convert(list, SysPermissionVo.class);
        }
        return menuList;

    }

    @Override
    public List<Long> listPermissionByRoleId(Long roleId) {

        SysRole role = roleMapper.selectById(roleId);
        if (role == null) {
            return CollUtil.newArrayList();
        }
        if (role.getRoleKey().equals("admin")) {
            LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysPermission::getStatus, StatusEnum.ENABLE.getCode());
            return permissionMapper.selectList(wrapper).stream().map(SysPermission::getPermissionId).toList();
        }
        return baseMapper.listPermissionByRoleId(roleId);
    }

    @Override
    public List<Tree<Long>> buildMenuTreeSelect(List<SysPermissionVo> permissions) {
        if (CollUtil.isEmpty(permissions)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(permissions, (menu, tree) -> {
            Tree<Long> menuTree = tree.setId(menu.getPermissionId())
                    .setParentId(menu.getParentId())
                    .setName(menu.getPermissionName());
            menuTree.put("menuType", menu.getPermissionType());
            menuTree.put("menuKey", menu.getPermissionKey());
        });
    }
    
    @Override
    public TableDataInfo<SysPermission> selectPageList(PageQuery pageQuery) {
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<>();
        // 按照排序号正序、创建时间倒序排列
        lqw.orderByAsc(SysPermission::getSortOrder)
           .orderByDesc(SysPermission::getCreateTime);
        
        Page<SysPermission> page = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }
}


